package controller

import (
	"net/http"
	"time"

	"gitee.com/liu_deping/gin-vue/db"
	"gitee.com/liu_deping/gin-vue/model"
	"gitee.com/liu_deping/gin-vue/response"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

type CategoryController struct { //让结构体实现接口
	DB gorm.DB
	//RestController
}

func NewCatgoryController() CategoryController {
	return CategoryController{
		DB: *db.DB.AutoMigrate(model.Category{}),
	}
}

// 插入数据
func (c *CategoryController) Add(ctx *gin.Context) {
	//获取参数
	name := ctx.PostForm("name")

	//验证参数
	if name == "" {
		response.Fail(ctx, nil, "数据验证错误,分类名称必填")
		return
	}
	//创建对象
	category := &model.Category{
		Name:      name,
		CreatedAt: time.Now(),
		UpdateAt:  time.Now(),
	}
	//写入数据库
	c.DB.Create(category)
	//响应前端
	response.Success(ctx, gin.H{"category": category}, "")
}

// 更新数据
func (c *CategoryController) Update(ctx *gin.Context) {
	//1.获取数据
	name := ctx.PostForm("name")
	id := ctx.PostForm("id")

	//2.验证数据格式
	if name == "" { //修改
		response.Fail(ctx, nil, "分类名称必填") //返回前端
		return
	}
	//3.验证数据库
	category := &model.Category{}
	c.DB.Where("id=?", id).First(category)
	if category.Name == "" { //不存在
		response.Response(ctx, http.StatusNotFound, 404, nil, "该类型不存在") //返回前端
		return
	}
	//写入数据库
	c.DB.Model(category).Where("id=?", id).Update(map[string]interface{}{
		"name":       name,
		"updated_at": time.Now(),
	})
	//响应前端
	response.Success(ctx, gin.H{"category": category}, "修改分类成功")
}

// 获取数据
func (c *CategoryController) GetAll(ctx *gin.Context) {
	//没有条件，数据格式检查由前端完成，并通过中间件鉴权
	category := []*model.Category{}
	c.DB.Find(&category)
	response.Success(ctx, gin.H{"category": category}, "获取成功")
}

// 删除数据
func (c *CategoryController) DeleteByID(ctx *gin.Context) {
	//获取待删除数据的ID
	id := ctx.PostForm("id")
	category := &model.Category{}
	//判断数据库是否存在该条数据
	c.DB.Where("id=?", id).First(category)
	if category.Name == "" { //不存在
		response.Response(ctx, http.StatusNotFound, 404, nil, "该类型不存在") //返回前端
		return
	}
	//删除满足前端提交的指定数据
	c.DB.Delete(category)
	response.Success(ctx, nil, "删除成功")
}
